package com.px.framework.web.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.px.common.constant.CacheConstants;
import com.px.common.constant.Constants;
import com.px.common.constant.UserConstants;
import com.px.common.core.domain.entity.SysRole;
import com.px.common.core.domain.entity.SysUser;
import com.px.common.core.domain.model.LoginUser;
import com.px.common.core.redis.RedisCache;
import com.px.common.enums.UserStatus;
import com.px.common.exception.ServiceAppException;
import com.px.common.exception.ServiceException;
import com.px.common.exception.user.*;
import com.px.common.utils.DateUtils;
import com.px.common.utils.MessageUtils;
import com.px.common.utils.SecurityUtils;
import com.px.common.utils.StringUtils;
import com.px.common.utils.ip.IpUtils;
import com.px.framework.manager.AsyncManager;
import com.px.framework.manager.factory.AsyncFactory;
import com.px.framework.security.context.AuthenticationContextHolder;
import com.px.system.domain.FlightUser;
import com.px.system.service.IFlightUserService;
import com.px.system.service.ISysConfigService;
import com.px.system.service.ISysRoleService;
import com.px.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 登录校验方法
 * 
 * @author WRJ
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IFlightUserService flightUserService;

    @Value("${token.soloLogin}")
    private boolean soloLogin;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {

        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());

        if (!soloLogin)
        {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = CacheConstants.LOGIN_WEB_USERID_KEY + loginUser.getUser().getUserId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey))
            {
                redisCache.deleteObject(userIdKey);
                redisCache.deleteObject(userKey);
            }
        }

        // 生成token
        return tokenService.createToken(loginUser);
    }

    public String appLogin(String username, String password)
    {

        // 登录前置校验
        loginAppPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new ServiceAppException(MessageUtils.message("user.password.not.match"));
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceAppException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());

        if (!soloLogin)
        {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = CacheConstants.LOGIN_APP_USERID_KEY + loginUser.getUser().getUserId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey))
            {
                redisCache.deleteObject(userIdKey);
                redisCache.deleteObject(userKey);
            }
        }
        // 生成token
        return tokenService.createAppToken(loginUser);
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
        // 判断角色是否能登录WEB端
        boolean isAllowPc = false;
        SysUser sysUser = userService.selectUserByUserName(username);
        String roleName = "";
        if (null != sysUser) {
            List<SysRole> roles = roleService.selectRolesByUserIdWithOutDataScope(sysUser.getUserId());
            if (CollectionUtil.isNotEmpty(roles)) {
                isAllowPc = roles.stream().filter(r -> null != r.getIsAllowWeb()).anyMatch(r -> 1 == r.getIsAllowWeb());
                roleName = roles.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
            }
        }
        if (!isAllowPc) {
            String errMsg = String.format("您的角色(%s)没有登录网页端的权限，请联系管理员添加权限", roleName);
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, errMsg));
            throw new RuntimeException(errMsg);
        }
    }

    public void loginAppPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new ServiceAppException(MessageUtils.message("not.null"));
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new ServiceAppException(MessageUtils.message("user.password.not.match"));
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new ServiceAppException(MessageUtils.message("user.password.not.match"));
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new ServiceAppException(MessageUtils.message("login.blocked"));
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public void recordFlightLoginInfo(Long userId)
    {
        FlightUser flightUser = new FlightUser();
        flightUser.setUserId(userId);
        flightUser.setLoginIp(IpUtils.getIpAddr());
        flightUser.setLoginDate(DateUtils.getNowDate());
        flightUserService.updateFlightUser(flightUser);
    }

    public String phoneLogin(String username, String password, String code, Integer type) {
        FlightUser user = new FlightUser();
        if( type == 0 ){//验证码
            // 用户名或验证码为空 错误
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(code))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
                throw new UserNotExistsException();
            }
            //验证码失效
            if(StringUtils.isNull(redisCache.getCacheObject(username + Constants.LOGIN))){
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaException();
            }
            //验证码错误
            if(!code.equals(redisCache.getCacheObject(username + Constants.LOGIN))){
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
            user = flightUserService.selectUserByUserName(username);
            userIsExist(user);
        }else if ( type == 1){//密码登录
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
                throw new UserNotExistsException();
            }
            user = flightUserService.selectUserByUserName(username);
            userIsExist(user);

            //判断密码是否正确
            if (!SecurityUtils.matchesPassword(password, user.getPassword()))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                        MessageUtils.message("user.password.retry.limit.count")));

                throw new UserPasswordNotMatchException();
            }
        }

        //记录登录信息
        recordFlightLoginInfo(user.getUserId());

//        if (!soloLogin)
//        {
//            // 如果用户不允许多终端同时登录，清除缓存信息
//            String userIdKey = CacheConstants.LOGIN_WEB_USERID_KEY + user.getUserId();
//            String userKey = redisCache.getCacheObject(userIdKey);
//            if (StringUtils.isNotEmpty(userKey))
//            {
//                redisCache.deleteObject(userIdKey);
//                redisCache.deleteObject(userKey);
//            }
//        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(Convert.convert(SysUser.class, user));
        loginUser.setUserId(user.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    private void userIsExist(FlightUser user) {
        String username = user.getUserName();
        if (StringUtils.isNull(user))
        {
            throw new ServiceException("登录用户：" + username + " 不存在");
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
    }


}
